<script setup>
import { ref, h } from 'vue'
import { VChip } from 'vuetify/components'

import { getRoles, createRoles, updateRoles, deleteRole, deleteBatch } from '@/api/roles.js'
import DataTable from '@/components/DataTable.vue'
import RoleEditDialog from '@/components/RoleEditDialog.vue'

const headers = [
  { title: '角色名称', key: 'name' },
  { title: '描述', key: 'description' },
  { title: '可查看标签', key: 'tags' },
  { title: '创建时间', key: 'createdAt' },
  { title: '更新时间', key: 'updatedAt' },
  { title: '操作', key: 'actions', sortable: false },
]

const rolesApi = {
  fetch: getRoles,
  create: createRoles,
  delete: deleteRole,
  deleteBatch: deleteBatch,
}

const slots = {
  tags: (item) => {
    return h(
      'div',
      { class: 'd-flex flex-wrap' },
      item.tags.map((tag) => h(VChip, { color: 'primary', variant: 'flat' }, tag)),
    )
  },
}

const tableRef = ref()
const showDialog = ref(false)
const editingRole = ref(null)
const refreshTrigger = ref(0)
const selectedRoles = ref([])

const openEdit = (role) => {
  editingRole.value = role
  showDialog.value = true
}

const handleSave = async (formData) => {
  if (editingRole.value) {
    await updateRoles(formData)
  } else {
    await createRoles(formData)
  }
  refreshTrigger.value++
}
</script>

<template>
  <h1>角色管理</h1>
  <v-spacer />
  <v-card-text>
    <DataTable
      ref="tableRef"
      v-model:selected="selectedRoles"
      :headers="headers"
      :downloadable="false"
      :api="rolesApi"
      :refresh-trigger="refreshTrigger"
      :slots="slots"
      @edit="openEdit"
      @create="openEdit(null)"
    />
  </v-card-text>

  <RoleEditDialog v-model="showDialog" :role="editingRole" @submit="handleSave" />
</template>
